//
//  LoginViewController.m
//  KuWoCan
//
//  Created by hwd on 17/3/2.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "LoginViewController.h"
#import "TextfiledView.h"
#import "NWLoginRequest.h"
#import "JKeyChainHelper.h"
#import "LoginUserModel.h"
#import "UserModel.h"
#import "MyMessageViewController.h"
#import "MySpecialSignVC.h"
#import "MBProgressHUD.h"
#import "RulesViewController.h"
#import "JinXCViewController.h"

@interface LoginViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UIButton *rulesButton;
@end

@implementation LoginViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:17.0]};

    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [self.navigationController.navigationBar setTranslucent:NO];
    if (iOS7Later) {
        [self.navigationController.navigationBar setBarTintColor:KwBlueColor];
    }else{
        [self.navigationController.navigationBar setTintColor:KwBlueColor];
    }
    [self setUpUI];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
     [self.view endEditing:YES];
    self.navigationController.navigationBarHidden = NO;
}

- (void)setUpUI
{
    UIImageView *bgView = [UIImageView new];
    bgView.image = kImg(@"BG");
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.left.right.equalTo(@0);
    }];
    
    TPKeyboardAvoidingTableView *tabView = [[TPKeyboardAvoidingTableView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStylePlain];
    tabView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.0];
    tabView.rowHeight = UITableViewAutomaticDimension;
    tabView.showsVerticalScrollIndicator = NO;
    tabView.estimatedRowHeight = 100.0;
    tabView.delegate = self;
    tabView.dataSource = self;
    tabView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:tabView];
    [tabView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bgView);
        make.left.equalTo(@(20 * screenW_6));
        make.right.equalTo(@(-20 * screenW_6));
        make.bottom.equalTo(@0);
    }];

    UILabel *ruleslabel = [[UILabel alloc] init];
    NSString *rulesString = @"我已阅读并同意服务条例";
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:rulesString];
    [attrString addAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:13 * screenW_6], NSForegroundColorAttributeName : [UIColor blackColor]} range:NSMakeRange(0, rulesString.length)];
//    [attrString addAttribute:NSForegroundColorAttributeName value:COLOR(158, 215, 242, .65) range:NSMakeRange(7, 4)];
    [attrString addAttribute:NSForegroundColorAttributeName value:KwColor(@"#024c91") range:NSMakeRange(7, 4)];
    ruleslabel.attributedText = attrString;
    [self.view addSubview:ruleslabel];
    [ruleslabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-20 * screenW_6);
    }];

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goRulesView)];
    ruleslabel.userInteractionEnabled = YES;
    [ruleslabel addGestureRecognizer:tap];

    self.rulesButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.rulesButton setImage:kImg(@"circle") forState:UIControlStateNormal];
    [self.rulesButton setImage:kImg(@"select") forState:UIControlStateSelected];
    self.rulesButton.backgroundColor = [UIColor clearColor];
    self.rulesButton.selected = YES;
    [self.rulesButton addTarget:self action:@selector(changeRulesStatus:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.rulesButton];
    [self.rulesButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(ruleslabel.mas_left).offset(-5 * screenW_6);
        make.centerY.equalTo(ruleslabel);
    }];
}

#pragma mark - EventResponse
- (void)changeRulesStatus:(UIButton *)sender {
    sender.selected = !sender.selected;
}

- (void)goRulesView {
    [self.navigationController pushViewController:[RulesViewController new] animated:YES];
}

#pragma mark - UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellId = @"cellId";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.row == 0)
    {
        UIImageView *headView = [UIImageView new];
        headView.image = kImg(@"LOGO");
        [cell addSubview:headView];
        [headView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(@(95 * screenW_6));
            make.centerX.equalTo(@0);
            make.size.mas_equalTo(CGSizeMake(202.5 * screenW_6, 126 * screenW_6));
            make.bottom.equalTo(@(-70 * screenW_6));
        }];
    }
    else if (indexPath.row == 1)
    {
        [self createCellContentViewWithCell:cell placehodelStr:@"请输入手机号码" imgStr:@"phone" indexPathRow:indexPath.row isPassword:NO];
    }
    else if (indexPath.row == 2)
    {
        [self createCellContentViewWithCell:cell placehodelStr:@"请输入密码" imgStr:@"password" indexPathRow:indexPath.row isPassword:YES];
    }
    else
    {
        UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [confirmBtn setTitle:@"登录" forState:UIControlStateNormal];
        confirmBtn.titleLabel.font = KwFont(17 * screenW_6);
        [confirmBtn setTitleColor:[UIColor colorWithHexString:@"0D64C9"] forState:UIControlStateNormal];
        confirmBtn.backgroundColor = [UIColor colorWithHexString:@"9ED7F2"];
        [confirmBtn addTarget:self action:@selector(goToLogin) forControlEvents:UIControlEventTouchUpInside];
        confirmBtn.alpha = .65;
        confirmBtn.layer.masksToBounds = YES;
        confirmBtn.layer.cornerRadius = 3 * screenW_6;
        [cell addSubview:confirmBtn];
        [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(@(-10 * screenW_6));
            make.top.equalTo(@(44 * screenW_6));
            make.height.equalTo(@(43 * screenW_6));
            make.left.equalTo(@(10 * screenW_6));
            make.right.equalTo(@(-10 * screenW_6));
        }];
    }
    cell.backgroundColor = [[UIColor clearColor] colorWithAlphaComponent:0.01];
    return cell;
}

- (void)createCellContentViewWithCell:(UITableViewCell *)cell placehodelStr:(NSString *)placehodelStr imgStr:(NSString *)imgStr indexPathRow:(NSInteger)indexPathRow isPassword:(BOOL)isPassword
{
    UIImageView *leftImg  = [UIImageView new];
    leftImg.image = kImg(imgStr);
    [cell addSubview:leftImg];
    [leftImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(10 * screenW_6));
        make.top.equalTo(@(24 * screenW_6));
        make.size.mas_equalTo(CGSizeMake(25 * screenW_6, 25 * screenW_6));
    }];
    
    UITextField *rightTxef = [UITextField new];
    rightTxef.font = KwFont(16 * screenW_6);
    if (isPassword)
    {
        rightTxef.secureTextEntry = YES;
    } else {
        rightTxef.keyboardType = UIKeyboardTypePhonePad;
    }
    rightTxef.tag = 100+indexPathRow;
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:placehodelStr attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName:[UIFont systemFontOfSize:16 * screenW_6]}];
    rightTxef.attributedPlaceholder = attrString;
    [cell addSubview:rightTxef];
    [rightTxef mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leftImg.mas_right).offset(15 * screenW_6);
        make.top.equalTo(leftImg);
        make.right.equalTo(cell);
//        make.centerY.equalTo(leftImg);
        make.bottom.equalTo(leftImg);
    }];
    
    if (isPassword)
    {
        UIButton *securePswBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [securePswBtn setImage:kImg(@"eyes") forState:UIControlStateNormal];
        [securePswBtn setImage:kImg(@"eye") forState:UIControlStateSelected];
        [securePswBtn addTarget:self action:@selector(showPassword:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:securePswBtn];
        [securePswBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(rightTxef.mas_right).offset(-15 * screenW_6);
            make.centerY.equalTo(rightTxef.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(30 * screenW_6, 25 * screenW_6));
        }];
    }

    UIView *line = [UIView new];
    line.backgroundColor = [UIColor whiteColor];
    [cell addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(leftImg.mas_bottom).offset(15);
        make.left.equalTo(leftImg.mas_left);
        make.right.equalTo(@-10);
        make.height.equalTo(@1.5);
        make.bottom.equalTo(@0);
    }];
}

- (void)showPassword:(UIButton *)securePswBtn
{
    securePswBtn.selected = !securePswBtn.selected;
    UITextField *pswTF = [self.view viewWithTag:102];
    pswTF.secureTextEntry = !pswTF.secureTextEntry;
}

-(void)goToLogin
{
    UITextField *nameTxtf = [self.view viewWithTag:101];
    NSString *nameStr = nameTxtf.text;
    
    UITextField *passwordTxtf = [self.view viewWithTag:102];
    NSString *pwStr = passwordTxtf.text;

    if (!isMobileNumber(nameStr)) {
        [SVProgressHUD showErrorWithStatus:@"请填写正确手机号"];
        return;
    }
    
    if (nameStr && nameStr.length > 0 && pwStr && pwStr.length > 0)
    {
        if (!self.rulesButton.isSelected) {
            [SVProgressHUD showErrorWithStatus:@"请阅读服务条例"];
            return;
        }
        NWLoginRequest *request = [[NWLoginRequest alloc] init];
        [request startRequestLoginWithLoginName:nameStr password:pwStr];
        [request completion:^(id result, NSString *message, id extension, BOOL succ) {
            if (succ)
            {
                //用户数据保存
                UserModel *user = [[UserModel alloc] initWithDictionary:result error:nil];
                
                //sqlite存储用户id
                [Singleton shareInstance].userId  = user.id;
                [Singleton shareInstance].isLogin = YES;
                [Singleton shareInstance].userType = user.userType;
                [user save];
                [NSUserDefaults saveBool:[result[@"signCode"] boolValue] forkey:@"signCode"];

                [JKeyChainHelper savePsaaword:pwStr psaawordService:kwPasswordService];

                if ([result[@"isCertification"] isEqualToString:@"0"] && [user.userType integerValue] == UserTypeAgency)
                {
                    //跳转到信息填写页面
                    MyMessageViewController *vc = [[MyMessageViewController alloc] init];
                    vc.isFirstWrite = YES;
                    [self.navigationController pushViewController:vc animated:YES];
                } else if (![user.signCode boolValue]) {
                    MySpecialSignVC *adressVC = [[MySpecialSignVC alloc]init];
                    adressVC.isFirstSubmit = YES;
                    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:adressVC.view animated:YES];
                    hud.mode = MBProgressHUDModeText;
                    hud.labelText = @"请填写签名";
                    [hud hide:YES afterDelay:2.f];
                    [self.navigationController pushViewController:adressVC animated:YES];
                }
//                else if ([result[@"isInit"] isEqualToString:@"0"] && [user.userType integerValue] == UserTypeAgency) {
//                    JinXCViewController *jinXC = [JinXCViewController new];
//                    jinXC.isFirstSubmit = YES;
//                    [self.navigationController pushViewController:jinXC animated:YES];
//                }
                else {
                    [SharedApp setRootViewController];
                    [self getUserInfo];
                }
                
                //登录后设置推送的标签别名
                NSString *kJPushTags = [Singleton shareInstance].userType;
                NSString *kJPushAlias = [Singleton shareInstance].userId;
                [JPUSHService setTags:[NSSet setWithArray:@[kJPushTags]] alias:kJPushAlias fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias){
                    NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, iTags, iAlias);
                }];
            }
            else
            {
                [SVProgressHUD showErrorWithStatus:message?:@"登陆失败"];
            }
        }];
        
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:@"请完善信息"];
    }
    
}

- (void)autoLoginUserLoginName:(NSString *)username password:(NSString *)pwStr {
    NWLoginRequest *request = [[NWLoginRequest alloc] init];
    [request startRequestLoginWithLoginName:username password:pwStr];
    [SVProgressHUD show];
    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        [SVProgressHUD dismiss];
        if (succ)
        {
            //用户数据保存
            UserModel *user = [[UserModel alloc] initWithDictionary:result error:nil];

            //sqlite存储用户id
            [Singleton shareInstance].userId  = user.id;
            [Singleton shareInstance].isLogin = YES;
            [Singleton shareInstance].userType = user.userType;
            [user save];
            [NSUserDefaults saveBool:[result[@"signCode"] boolValue] forkey:@"signCode"];

            [JKeyChainHelper savePsaaword:pwStr psaawordService:kwPasswordService];

            if ([result[@"isCertification"] isEqualToString:@"0"] && [user.userType integerValue] == UserTypeAgency)
            {
                //跳转到信息填写页面
                MyMessageViewController *vc = [[MyMessageViewController alloc] init];
                vc.isFirstWrite = YES;
                [self.navigationController pushViewController:vc animated:YES];
            } else if (![user.signCode boolValue]) {
                MySpecialSignVC *adressVC = [[MySpecialSignVC alloc]init];
                adressVC.isFirstSubmit = YES;
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:adressVC.view animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.labelText = @"请填写签名";
                [hud hide:YES afterDelay:2.f];
                [self.navigationController pushViewController:adressVC animated:YES];
            }
//            else if ([result[@"isInit"] isEqualToString:@"0"]&& [user.userType integerValue] == UserTypeAgency) {
//                JinXCViewController *jinXC = [JinXCViewController new];
//                jinXC.isFirstSubmit = YES;
//                [self.navigationController pushViewController:jinXC animated:YES];
//            }
            else {
                [SharedApp setRootViewController];
                [self getUserInfo];
            }

            //登录后设置推送的标签别名
            NSString *kJPushTags = [Singleton shareInstance].userType;
            NSString *kJPushAlias = [Singleton shareInstance].userId;
            [JPUSHService setTags:[NSSet setWithArray:@[kJPushTags]] alias:kJPushAlias fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias){
                NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, iTags, iAlias);
            }];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:message];
        }
    }];
}

//将用户信息存入NSUserDefaults
- (void)getUserInfo
{
    NWLoginRequest *request = [[NWLoginRequest alloc] init];
    NSString *userId = [Singleton shareInstance].userId;
    [request startRequestGetUserInfoWithId:userId];
    [request completion:^(id result, NSString *message, id extension, BOOL succ) {
        NSLog(@"%@__________%d",result,succ);
        if (succ)
        {
            LoginUserModel *model = [[LoginUserModel alloc] initWithDictionary:result error:nil];
            [NSUserDefaults saveObject:model.businessLicense forKey:@"businessLicense"];
            [NSUserDefaults saveObject:model.autograph forKey:@"autograph"];
            [NSUserDefaults saveObject:model.salesChannel forKey:@"salesChannel"];
            [NSUserDefaults saveObject:model.bankCard forKey:@"bankCard"];
            [NSUserDefaults saveObject:model.brand forKey:@"brand"];
            [NSUserDefaults saveObject:model.realName forKey:@"realName"];
            [NSUserDefaults saveObject:model.car forKey:@"car"];
            [NSUserDefaults saveObject:model.acreage forKey:@"acreage"];
            [NSUserDefaults saveObject:model.id forKey:@"id"];
            [NSUserDefaults saveObject:model.teams forKey:@"teams"];
            [NSUserDefaults saveObject:model.salesArea forKey:@"salesArea"];
            [NSUserDefaults saveObject:model.registeredCapital forKey:@"registeredCapital"];
            [NSUserDefaults saveObject:model.foodCertificate forKey:@"foodCertificate"];
            [NSUserDefaults saveObject:model.bankName forKey:@"bankName"];
            [NSUserDefaults saveObject:model.experience forKey:@"experience"];
            
        }
    }];
}

@end
